<script>
import { getCategoryByIdAjax, saveOrUpdate } from '@/data/CategoryData'

const formData = {}
export default {
  name: 'CategoryEdit',
  data () {
    return {
      show: false,
      category: { ...formData },
      rules: {
        name: [
          { required: true, message: '分类名不能为空' }
        ]
      }
    }
  },
  methods: {
    getCategory (id) {
      this.category = { ...formData }
      this.show = true
      if (id) {
        const res = getCategoryByIdAjax(id)
        if (res.code === 200) {
          this.category = { ...res.data }
        } else {
          this.$alert(res.msg, { type: 'error' })
        }
      }
    },
    submit () {
      this.$refs.formData.validate(valid => {
        if (valid) {
          const res = saveOrUpdate(this.category)
          if (res.code === 200) {
            this.$message.success(`${this.category.id ? '修改' : '添加'}成功`)
            this.show = false
            this.$emit('close')
          } else {
            this.$alert(res.msg, { type: 'error' })
          }
        }
      })
    }
  }
}
</script>

<template>
  <el-dialog v-if="show" :visible.sync="show" title="分类编辑页">
    <el-form ref="formData" :model="category" :rules="rules" label-width="80px">
      <el-form-item label="分类名" prop="name">
        <el-input v-model="category.name" placeholder="分类名"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped>

</style>
